<!--w-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>商品展示</title>
    <!-- 引入 jQuery -->
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <!-- 引入 Bootstrap 核心 CSS -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 引入 Bootstrap 核心 JavaScript -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="client.css">
</head>
<body>

<!--dingbudaohang <-->
<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container-fluid nav-container">
        <div class="navbar-header">
            <a class="navbar-brand shop-name" href="#">🌟 重庆对外经贸商店</a>
        </div>

        <div class="nav-middle">
            <input type="text" class="form-control search-input" placeholder="请输入商品关键词...">
            <button class="btn btn-success search-btn">搜索</button>
        </div>

        <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><span class="glyphicon glyphicon-shopping-cart"></span></a></li>
            <li id="loginNav"><a href="#" id="loginBtn">登录</a></li>
            <li id="registerNav"><a href="#" id="registerBtn">注册</a></li>
            <button id="logoutBtn">退出</button>
        </ul>
    </div>
</nav>

<!-- 商品列表展示 -->
<div class="container content-container" style="margin-top: 80px;">
    <div class="row goods-list">
        <!-- 商品卡片会动态生成 -->
    </div>

    <!-- 分页 -->
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            <!-- 分页按钮会在这里渲染 -->
        </ul>
    </nav>
</div>

<!-- 分页控件 -->
<div class="container">
    <div class="row">
        <div class="col-sm-12 text-center">
            <ul class="pagination">
                <li><a href="#" id="firstPage">首页</a></li>
                <li><a href="#" id="prevPage">上一页</a></li>
                <li><a href="#" id="nextPage">下一页</a></li>
                <li><a href="#" id="lastPage">末页</a></li>
            </ul>
        </div>
    </div>
</div>

<!-- 注册弹窗 -->
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="registerForm">
                <div class="modal-header">
                    <h4 class="modal-title" id="registerModalLabel">用户注册</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group"><input name="account" class="form-control" placeholder="账号"></div>
                    <div class="form-group"><input name="password1" type="password" class="form-control" placeholder="密码"></div>
                    <div class="form-group"><input name="realname" class="form-control" placeholder="真实姓名"></div>
                    <div class="form-group"><input name="idcard" class="form-control" placeholder="身份证号"></div>
                    <div class="form-group"><input name="tel" class="form-control" placeholder="手机号"></div>
                    <div class="form-group"><input name="age" type="number" class="form-control" placeholder="年龄"></div>
                    <div class="form-group"><input name="province" class="form-control" placeholder="省份"></div>
                    <div class="form-group"><input name="city" class="form-control" placeholder="城市"></div>
                    <div class="form-group"><input name="district" class="form-control" placeholder="区"></div>
                    <div class="form-group"><input name="addr" class="form-control" placeholder="详细地址"></div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">注册</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 登录弹窗 -->
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="loginForm">
                <div class="modal-header">
                    <h4 class="modal-title" id="loginModalLabel">用户登录</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group"><input name="account" class="form-control" placeholder="账号"></div>
                    <div class="form-group"><input name="password1" type="password" class="form-control" placeholder="密码"></div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">登录</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>

                </div>
                <button id="logoutButton"  class="btn-success"  onclick="logout()">退出</button>
            </form>
        </div>
    </div>
</div>


</body>

<script>
    $(function () {
        let currentPage = 1;  // 当前页数
        let pageSize = 8;     // 每页显示的商品数量

        // 初始加载商品数据
        loadGoods(currentPage, pageSize);

        // 加载商品数据
        function loadGoods(page, size) {
            $.ajax({
                url: 'allGoods',  // 后端接口地址
                method: 'GET',
                data: { page: page, size: size },  // 传递分页参数
                dataType: 'json',
                success: function (res) {
                    if (res.code === 200) {
                        renderGoods(res.data);
                        handlePagination(res.data.length);  // 根据返回的商品数量来判断分页按钮状态
                    } else {
                        $('.goods-list').html('<p class="text-danger">' + res.msg + '</p>');
                    }
                },
                error: function () {
                    $('.goods-list').html('<p class="text-danger">加载商品失败！</p>');
                }
            });
        }

        // 渲染商品
        function renderGoods(goodsList) {
            let html = '';
            $.each(goodsList, function (index, good) {
                let imgUrl = good.img || 'https://via.placeholder.com/150';  // 默认图片
                html += `
                <div class="col-sm-6 col-md-3">
                    <div class="thumbnail">
                        <img src="${imgUrl}" alt="商品图片" class="img-responsive">
                        <div class="caption">
                            <h4>${good.title}</h4>
                            <p>￥<span class="price-new">${good.price.toFixed(2)}</span> <del class="price-old">￥50.00</del></p>
                            <p><a href="#" class="btn btn-primary" role="button">加入购物车</a></p>
                        </div>
                    </div>
                </div>`;
            });
            $('.goods-list').html(html);
        }

        // 处理分页按钮的显示/隐藏状态
        function handlePagination(currentPageDataCount) {
            const isLastPage = currentPageDataCount < pageSize;  // 如果当前页的数据量小于 pageSize，说明是最后一页

            // 控制分页按钮的禁用状态
            $('#firstPage').prop('disabled', currentPage === 1);
            $('#prevPage').prop('disabled', currentPage === 1);
            $('#nextPage').prop('disabled', isLastPage);  // 如果是最后一页，禁用“下一页”
            $('#lastPage').prop('disabled', isLastPage);  // 如果是最后一页，禁用“末页”

            // 为分页按钮绑定点击事件
            $('#firstPage').off('click').on('click', function () {
                loadGoods(1, pageSize);
                currentPage = 1;  // 更新当前页为首页
            });

            $('#prevPage').off('click').on('click', function () {
                if (currentPage > 1) {
                    loadGoods(currentPage - 1, pageSize);
                    currentPage--;  // 更新当前页
                }
            });

            $('#nextPage').off('click').on('click', function () {
                loadGoods(currentPage + 1, pageSize);
                currentPage++;  // 更新当前页
            });

            $('#lastPage').off('click').on('click', function () {
                loadGoods(currentPage + 1, pageSize);  // 这里可以根据实际需要调整逻辑，或者使用总页数
                currentPage++;  // 更新当前页
            });
        }
    });
</script>

<!-- 点击注册和登录，退出按钮弹出注册框 -->
<script>

    // 登录成功时显示退出按钮
    function onLoginSuccess() {
        document.getElementById('logoutButton').style.display = 'block';
    }

    // 退出功能
    function logout() {
        // 清除本地存储的用户信息（例如，sessionStorage 或 localStorage）
        sessionStorage.removeItem('user'); // 假设使用 sessionStorage 保存登录信息

        // 跳转到登录页面或首页
        window.location.href = '/client.html';  // 替换为您的登录页面地址

        // 隐藏退出按钮
        document.getElementById('logoutButton').style.display = 'none';
    }

    $(function () {
        // 打开登录弹窗
        $('#loginBtn').click(function () {
            $('#loginModal').modal('show');
        });

        // 提交登录表单
        $('#loginForm').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: 'Clogin',
                method: 'POST',
                data: $(this).serialize(),
                success: function (res) {
                    if (res.code === 200) {
                        alert('登录成功！欢迎你：' + res.username);
                        $('#loginModal').modal('hide');

                        // 替换“登录”为欢迎语，移除注册
                        $('#loginNav').html(`<a href="#">欢迎，${res.username}</a>`);
                        $('#registerNav').remove();
                    } else {
                        alert(res.msg || '登录失败');
                    }
                },
                error: function () {
                    alert('请求失败');
                }
            });
        });
    });


    $(function () {
        $('a:contains("注册")').click(function () {
            $('#registerModal').modal('show');
        });

        $('#registerForm').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: 'register',
                method: 'POST',
                data: $(this).serialize(),
                success: function (res) {
                    if (res.code === 200) {
                        alert('注册成功！');
                        $('#registerModal').modal('hide');
                    } else {
                        alert(res.msg || '注册失败！');
                    }
                },
                error: function () {
                    alert('请求失败');
                }
            });
        });
    });
</script>

<script>
    document.getElementById("logoutBtn").addEventListener("click", function() {
        // 发送退出请求
        fetch("logout", {
            method: "GET"
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    alert('退出成功，感谢使用');  // 提示用户退出成功
                    window.location.href = "client.html";  // 跳转到登录页面
                } else {
                    alert("退出失败，请稍后再试！");
                }
            })
            .catch(error => {
                console.error("退出请求失败:", error);
            });
    });
</script>

</html>
